from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
import json
from .models import *

# Create your views here.
@require_http_methods(["POST","OPTIONS"])
def login_post(request):
    if request.method == "OPTIONS":
        return JsonResponse({"status":200})
    if request.method == 'POST':
        #解包
        number = json.loads(request.body.decode('utf-8'))['number']
        password = json.loads(request.body.decode('utf-8'))['password']
        #从数据库中获取
        try:
            # 根据用户名查找用户
            user = Users.objects.get(username=number)
            if user.password == password:
                print("登录成功")
                return JsonResponse({'status': 1001})  # 验证通过
            else:
                print("密码错误")
                return JsonResponse({'status': 1002})  # 密码错误
        except Users.DoesNotExist:
            print("用户不存在")
            return JsonResponse({'status': 1003})  # 用户不存在
        #1001代表登录成功，1000代表登录失败
    return JsonResponse({'status': 1000})

@require_http_methods(["POST","OPTIONS"])
def regis_post(request):
    if request.method == "OPTIONS":
        return JsonResponse({"status":200})
    if request.method == 'POST':
        number = json.loads(request.body.decode('utf-8'))['number']
        password = json.loads(request.body.decode('utf-8'))['password']
        user_type = json.loads(request.body.decode('utf-8'))['radio']
        #验证账号是否已经存在
        try:
            is_ok = Users.objects.get(username=number)
            print("注册账号已经存在")
            return JsonResponse({'status': 1002})
        except Users.DoesNotExist:
            new=Users.objects.create(username=number, password=password, user_type=user_type)
            if new.password == password:
                print("注册成功")
                return JsonResponse({'status': 1001})
    return JsonResponse({'status': 1000})